package com.jfs.health;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Description 心跳管理者
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022-08-23
 */
public class HealthCheckReactor {
    private final ScheduledExecutorService scheduledExecutorService;

    public HealthCheckReactor(ScheduledExecutorService scheduledExecutorService) {
        this.scheduledExecutorService = scheduledExecutorService;
    }

    /**
     * 存储所有定时任务
     */
    private static Map<String, ScheduledFuture> FUTURE_MAP = new ConcurrentHashMap<>();

    /**
     * 执行心跳任务检查
     *
     * @param task
     * @param initialDelay
     * @param delay
     */
    public ScheduledFuture<?> scheduleCheck(HealthCheckTask task, long initialDelay, long delay) {
        task.setStartTime(System.currentTimeMillis());
        stopSeceduleCheck(task.taskKey());
        ScheduledFuture<?> scheduledFuture = this.scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, TimeUnit.MILLISECONDS);
        FUTURE_MAP.put(task.taskKey(), scheduledFuture);
        return scheduledFuture;
    }

    /**
     * 清除定时任务
     *
     * @param key
     */
    public void stopSeceduleCheck(String key) {
        if (FUTURE_MAP.containsKey(key)) {
            ScheduledFuture scheduledFuture = FUTURE_MAP.get(key);
            scheduledFuture.cancel(true);
            FUTURE_MAP.remove(scheduledFuture);
        }
    }
}
